package cn.kgc.vue.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.kgc.vue.anno.LogAnnotation;
import cn.kgc.vue.common.Operation;
import cn.kgc.vue.common.ResponseResult;
import cn.kgc.vue.common.ResponseStatus;
import cn.kgc.vue.dto.UserPageDTO;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.form.AddUserForm;
import cn.kgc.vue.form.PasswordForm;
import cn.kgc.vue.form.UserLoginForm;
import cn.kgc.vue.service.UserService;
import cn.kgc.vue.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/8/8
 * @Description:
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    // 获取用户列表
    @GetMapping("page")
    @LogAnnotation(model = "用户模块",operation = Operation.SELECT)
    public ResponseResult getPageList(UserPageDTO userPageDTO) {
        return userService.getUserPage(userPageDTO);
    }

    // 获取用户个人信息
    @GetMapping("personalInfo")
    @LogAnnotation(model = "用户模块",operation = Operation.SELECT)
    public ResponseResult getPersonalInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        //解析token  获取 userId
        Integer userId = (Integer) JWTUtil.getClaim(token).get("userId");
        User user = userService.getById(userId);

        ResponseResult responseResult = new ResponseResult();
        responseResult.success(ResponseStatus.SUCCESS, user);
        return responseResult;
    }


    // getById
    @GetMapping("getById")
    @LogAnnotation(model = "用户模块",operation = Operation.SELECT)
    public ResponseResult getPersonalInfo(Integer id) {
        return userService.getUserById(id);
    }


    // 编辑用户个人信息  editPersonalInfo
    @PutMapping("editPersonalInfo")
    @LogAnnotation(model = "用户模块",operation = Operation.UPDATE)
    public ResponseResult editPersonalInfo(@RequestBody User user) {

        userService.updateById(user);
        ResponseResult responseResult = new ResponseResult();
        responseResult.success();
        return responseResult;
    }


    // 修改用户状态  updateState
    @PutMapping("updateState")
    @RequiresPermissions("sys:user:update")
    @LogAnnotation(model = "用户模块",operation = Operation.UPDATE)
    public ResponseResult updateState(@RequestBody User user) {
        userService.updateById(user);
        ResponseResult responseResult = new ResponseResult();
        responseResult.success();
        return responseResult;
    }


    //批量删除用户数据    根据角色限定权限
    @RequiresPermissions("sys:user:delete")
    @LogAnnotation(model = "用户模块",operation = Operation.DELETE)
    @DeleteMapping("batchDelete")
    public ResponseResult batchDelete(@RequestBody Integer[] ids) {
        List<Integer> uIds = Arrays.asList(ids);
        return userService.removeBatch(uIds);
    }


    // 修改个人密码
    @PutMapping("editPassword")
    public ResponseResult editPassword(@RequestBody PasswordForm passwordForm, HttpServletRequest request) {

        String token = request.getHeader("token");
        Integer userId = (Integer) JWTUtil.getClaim(token).get("userId");

        User user = userService.getById(userId);
        String password = user.getPassword();  //  密文

        String oldPassword = passwordForm.getOldPassword(); //  原始密码  明文
        oldPassword = new Md5Hash(oldPassword, user.getSalt(), 1024).toHex();

        if (!StringUtils.equals(password, oldPassword)) {
            throw new IncorrectCredentialsException();
        }

        // 将新密码加密处理
        String newPassword = new Md5Hash(passwordForm.getNewPassword(), user.getSalt(), 1024).toHex();

        LambdaUpdateWrapper<User> lambda = new UpdateWrapper<User>().lambda();
        lambda.eq(User::getId, userId).set(User::getPassword, newPassword);
        userService.update(lambda);

        ResponseResult responseResult = new ResponseResult();
        responseResult.success();
        ;
        return responseResult;
    }

    //登录请求
    @PostMapping("login")
    public ResponseResult login(@RequestBody UserLoginForm userLoginForm) {
        return userService.login(userLoginForm);
    }

    @RequiresPermissions({"sys:role:update","sys:role:add"})
    @LogAnnotation(model = "用户模块",operation = Operation.UPDATE)
    @PostMapping("addOrUpdate")
    public ResponseResult addOrUpdateUser(@RequestBody AddUserForm addUserForm) {

        if (ObjectUtil.isNotNull(addUserForm.getId())) {
            return userService.updateUser(addUserForm);
        }
        return userService.addUser(addUserForm);
    }

    // 加载用户菜单
    @GetMapping("menu")
    public ResponseResult getMenu(HttpServletRequest request) {
        return userService.getMenu(request);
    }


}
